<template>
  <div>
    <div style="display: inline-flex">
      <Input
        v-model="deptName"
        readonly
        style="margin-right:10px;"
        :placeholder="placeholder"
        :clearable="clearable"
        @on-clear="clearSelect"
      />
      <Poptip transfer trigger="click" placement="right" title="选择部门">
        <Button icon="md-list">选择部门</Button>
        <div slot="content">
          <Input
            v-model="searchKey"
            suffix="ios-search"
            @on-change="searchDept"
            placeholder="输入部门名搜索"
            clearable
          />
          <div class="dep-tree-bar">
            <Tree
              :data="deptData"
              @on-select-change="selectTree"
              :multiple="false"
            ></Tree>
            <Spin size="large" fix v-if="deptLoading"></Spin>
          </div>
        </div>
      </Poptip>
    </div>
  </div>
</template>

<script>
import {getDeptTree,searchDept} from "@/api/dept";
export default {
  name: "dept-tree-select",
  props:{
    clearable: {
      type: Boolean,
      default: true
    },
    placeholder: {
      type: String,
      default: "点击选择部门"
    }
  },
  data(){
    return{
      deptName:'',
      searchKey:'',
      deptLoading:false,
      deptData:[],
      deptId:[]
    }
  },
  methods:{
    clearSelect(){
      this.deptId=[];
      this.deptName='';
      this.getDeptTreeData();
      if (this.multiple) {
        this.$emit("on-change", []);
      } else {
        this.$emit("on-change", "");
      }
      this.$emit("on-clear");
    },
    searchDept(){
      searchDept({searchText:this.searchKey}).then(res=>{
        if(res.code===200){
          this.deptData=res.data
        }
      })
    },
    setData(deptId,deptName){
      this.deptName = deptName;
      this.deptId = [];
      this.deptId.push(deptId);
      this.$emit("on-change", this.deptId);
    },
    selectTree(v){
      let ids=[];
      let title='';
      v.forEach(e=>{
        ids.push(e.deptId);
        if(title===''){
           title=e.title;
        }else{
          title=title+'、'+e.title
        }
      })
      this.deptName=title;
      this.deptId=ids;
      this.$emit('on-change',this.deptId[0])
    },
    getDeptTreeData() {
      getDeptTree().then(res=>{
        if(res.code===200){
          this.deptData=res.data;
        }
      })
    },
  },
  mounted(){
    this.getDeptTreeData();
  }
}
</script>

<style scoped>

</style>
